package user

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay/wechat"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"gorm.io/gorm"
	"log"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

var (
	mchID                      = "1662979262"
	mchAPIv3Key                = "sharesharesharesharesharesharesh"
	mchCertificateSerialNumber = "528C62CBC3C66FF2A6E8F35B5B29C5874E3F7548"
	mchPrivateKey              = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8tiouNjBw4PtE\npun5lXohGOx5yjbt1O0XdH6KWQtQEOB/9DiKGfsaE5qVdGcBSb9L1o/rM46MSogw\naztDWZdhLfxQWu/Mtp/3dXrQuwnQFlsE7fwNZa/OT67Nrm4z9aqnruKcZLcYbwnR\nSnJCAc7jaJiPco7mt69LKYZFX1pOGo7m1F6GEFCDRRon6CfMb1Lh0tcDXkClDMZw\nITd/1zJTDfItmDLSp/UQBWlt16SNWrIA3iah/gYS3zR8UBECxNjtaja+/6zpY3P+\ncwC3idk2g0KotQIfJNEMQMCImGcVck34h+rO8l/tpOzsdJLSm8cjBfHfkxUbdx/D\nYfVwsN29AgMBAAECggEBAJNqyrCm7FiBqEgNDCJIvss0KSdK7HYGK+ByxJdW0BuP\n05ChO7nGaf4I6m1uLTk4XxPjXTIjaGv3nUQVwInwZu0nez9aipGk6HnrcDG2qwe/\nLwM+1fOxSBEm9ir+5F/6vYGYgLYjh1SzCTxRp8ggmXnUr7j/iNp7C5jvq1BuGKGB\njI7+dwg6SupnA7VD+23AGg6w9Aea7rBtG/X1fw3CQC0FRcZugTVSxfri93AOcmpv\nSkFK2XqsVN2XqQx8b3cJ8kH0JEhkhoYbsZ5ZQ+D0ayfTk156lCYkIfx0P++7GisO\nzttcfBAOu+QplAZeY/ZRsYU7eW53K7auuyakZCOnSoECgYEA8zErqcIsMvhedBVO\nWqYul2g/xWOwA95flbcw/G7EZC6i2ZgYmLFG+kfsHFSe6Cyzqe7J6H4LbJV8Z2Vq\nViwZTLeEVA49jWZFZBMDNOQYYNzOtWE8rWhduOpgsEtpt42W7QG/VFKLCbbw83ez\nsUqgF3WubAhy+R8G81CchcPqoVkCgYEAxqZ2c7oGD/VCdyCp1tJPA6/Df7/jaPuU\n6A+3yABdmfY6PP0BUGKvG/S3s7EBCgTqsYA9/fzgI/Nz2WjgWYN5/1HtnWwg/vTa\n8DT876M87OsVPlKfBVL9Ds8EgRuf4pBaTJJRqVMgXxmSynkAby2/cTzT/8zXc+dY\nJIA27mJzjwUCgYBDlnjSFzr9d3WYwYsjOmhcgAapL0lt6dGa5Gzi204NocB0xQag\n+TQGvxJp1ULMuA++vLS0vsMiDHGkstTY2iy125MVYVfOAoxqgbY0bugvk26Hjly0\nvPq/N7RjirH454r4l7G7F624p3VT1QLF1T2lB3nQYJDDl9HwsYiuzIJbEQKBgQCg\ng0M1MXvSiy/AiHETtu3Hoc8LO6bqXlasyH6Mqdb4H+BhBWJ5bLPnl+6T0JNxYBWv\nhVsSDrGh+waCBt85FSaPqsigKg3jVUBPVdGHZNRG75FDwYjiyXLW82nFVOf1LwT3\n2EcJ1bRTg5t75Rf3vfRx8F+w0vjIm4c6PyujpYOQbQKBgH1Dg0nHd6DVypS8SpED\nmXe0JVSIx6QrOF9k4/8sAt3n0N9H2PL2YiDQlei4U3RN1Rco0WZYPzSj2H8hP87b\n7voABdXNoaWw8nLNlxfWxMz951gkly3IqLEma6RCCyHEFdOLQyZlO+6UjJbG3znh\nfCyWk5N3C2mbqinom3FL9ifd\n-----END PRIVATE KEY-----"

	mchCertificateSerialNumberywd = "4BD5BD7EA96E52C3806F970B36C1EC7990B205C7"
	mchPrivateKeyywd              = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADAN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DGPAjj1x9OBv93L5BspsVejqWR0xMXPLAQFhebXw\nTBqsGJe+5QKBgQCWh4SK1YgJmsJh8QSKi8iOtyd6S3rDcFrt4+8sOmxz9/X43SkY\nhUVnxq6lZm8ynGHBiJ4e6lwliqfi2W7FfDqJ4vSMWY2/PnooRzk0r/O2FlY94QPb\nlxv8PJ+lIhppKQHPF9iWxXv7Rw60o+piKvlHqTxJ7mRbrQztU35JJRdfhQKBgAyE\nHuoOs4sl0GPz6Tj/JskzGwOKGMByysXCTpHrNbJ0eOFmM94assZ5gaYFBw4g77mD\nljH8TF3B4UwwJ9l80C872IzPjqW/uko/9y5nZkRx7O2Y1PQbW+QB8i7ZzD0RZRsB\n3SaBAMg2uVusveAs8prI6N9rz6dDz64TQrMu0gNVAoGBAOcYXi42pdsY8uwJo8Y5\n+EIpo6WaEivzUW5tIxDB1K23noA48roKhjYQj0hjjH24U01YCJtZzN3XGv1IIN+Y\n2XiSFf0r/MMh3UA8J7mrapzc2ndVevamCjPuBz4TkEa1A+YnlIMUA6wF/EWRtF7i\nvj5btWof7Wu5u9lS2XkUJu81\n-----END PRIVATE KEY-----"
)

// 微信支付
func Wechatpaynew(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	//id := request.ID
	uid := request.Uid
	price := request.Price
	//var pkg models.Buypackage
	//data_source.Db.Where("id = ?", id).First(&pkg)
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	//if user.Guanlian == 1 {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    400,
	//		"error":   1,
	//		"success": 400,
	//		"data":    "on",
	//		"msg":     "没有购买权限",
	//	})
	//	return
	//}
	orderno := Generate(time.Time{})

	orderadd := models.Buyorder{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   price,
	}
	data_source.Db.Create(&orderadd)

	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("upload/apiclient_key.pem")

	if err != nil {
		log.Print("load merchant private key error")
	}

	ctx1 := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
	}
	client, err := core.NewClient(ctx1, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err)
	}

	svc := jsapi.JsapiApiService{Client: client}
	resp, result, err := svc.PrepayWithRequestPayment(ctx1,
		jsapi.PrepayRequest{
			Appid:         core.String(appId),
			Mchid:         core.String(mchId),
			Description:   core.String("公仔"),
			OutTradeNo:    core.String(orderno),
			TimeExpire:    core.Time(time.Now()),
			NotifyUrl:     core.String(pturl + "/user/wechatNotifynew"),
			SupportFapiao: core.Bool(false),
			Amount: &jsapi.Amount{
				Currency: core.String("CNY"),
				Total:    core.Int64(100),
			},
			Payer: &jsapi.Payer{
				Openid: core.String(user.RoutineOpenid),
			},
		},
	)
	fmt.Println(resp)
	fmt.Println("----------------------------")
	fmt.Println(result)
	if err != nil {
		// 处理错误
		log.Printf("call Prepay err:%s", err)
	} else {
		// 处理返回结果
		log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
	}
	//ctx.JSON(http.StatusOK, gin.H{
	//	"code":    0,
	//	"msg":     "ok",
	//	"error":   0,
	//	"success": 200,
	//	"data":    data,
	//})
	return
}

// @Summary 微信支付回调
// @Produce  json
// @Success 200 {string} string "success"
// @Router /v1/wechat_notify [post]
func WechatNotifynew(c *gin.Context) {

	notifyRsp, err := wechat.ParseNotifyToBodyMap(c.Request)
	//fmt.Println(notifyRsp)
	if err != nil {
		c.String(200, "error")
		return
	}
	ok, errSign := wechat.VerifySign(apiKey, wechat.SignType_MD5, notifyRsp)
	if ok { // 验证成功
		fmt.Println("errSign = ", errSign)
		//fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupay(notifyRsp["out_trade_no"].(string))
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}

// 支付完成
func Zhifupaynew(order string) {
	var orders models.Buyorder
	data_source.Db.Where("orderno = ?", order).First(&orders)
	data_source.Db.Model(&models.Buyorder{}).Where("orderno = ?", order).Update("status", 2)
	data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).UpdateColumn("price", gorm.Expr("price + ?", orders.Price))
}
